var day = null;
var list = null;

$(function()	//Document.ready function
{	

	// Set the style of the default content (schedule) link
	$('#schedule').addClass("selectedLink");
	
	// Accordion links
	$("#accordion").accordion(
	{ header: "h3" 
	});

	// Check whether or not the user wants to use the default time server or not (on page load)	
	if($('#useDefaultTimeServer').attr('checked'))
	{
		$('#timeServerField').hide();

	}
	else{
		$('#timeServerField').show();
	}

	// Check whether or not the user wants to use the default time server or not
	$('#useDefaultTimeServer').click(function(){
		if($('#useDefaultTimeServer').attr('checked'))
		{
			$('#timeServerField').fadeOut("medium")();
	
		}
		else{
			$('#timeServerField').fadeIn("medium")();
		}
	})	;
	

	// Check whether or not the user wants to synchronize the time with a time server or not (on page load)		
	if($('#autoTimeSync').attr('checked'))
	{
		$('#timeSettingsFields').show();	
	}
	else{
		$('#timeSettingsFields').hide();
	}
		
	// Check whether or not the user wants to synchronize the time with a time server or not
	$('#autoTimeSync').click(function(){
		if($('#autoTimeSync').attr('checked'))
		{
			$('#timeSettingsFields').fadeIn("medium");	
		}
		else{
			$('#timeSettingsFields').fadeOut("medium");
		}
	});
		
	/*
	 * Dialog boxes
	 */

	// Invalid settings information dialog boxes
	$("#settingsIncomplete, #invalidDHCP, #invalidMAC, #invalidIP, #invalidSubnet, #invalidGateway, #invalidDNS, #invalidSSID, #invalidWEPKey, #invalidTempDialog, #timeExistsDialog, #invalidTimeDialog, #maxSettingsDialogMultiple, #maxSettingsDialog, #manualModeDialog2, #switchingToScheduleDialog2, #settingsNotLoaded, #settingsSaved, #settingsNotSaved").dialog({
			modal: true,
			autoOpen: false,
			resizable: false,
			zIndex: 2,
			buttons: {
				Ok: function() {
					$(this).dialog('close');
				}
			}
	});
							
	/*
	 * Lets the user know that they are about to override the current operation mode
	 */					
	$("#manualModeDialog").dialog({
			modal: true,
			autoOpen: false,
			resizable: false,
			zIndex: 2,
			buttons: {
				Yes: function() {
					$(this).dialog('close');
					setOpMode("Manual");
					//$('#manualModeDialog2').dialog('open');
					saveSettings();
				},
				No: function(){
					$(this).dialog('close');
				}
			}
	});
	
	/*
	 * Lets the user know that they are about to override the current operation mode
	 */					
	$('#switchingToScheduleDialog').dialog({
			modal: true,
			autoOpen: false,
			resizable: false,
			zIndex: 2,
			buttons: {
				Yes: function() {
					$(this).dialog('close');
					setOpMode("Schedule");
					saveSettings(true);
					//$('#switchingToScheduleDialog2').dialog('open');
				},
				No: function(){
					$(this).dialog('close');
					saveSchedule();
				}
			}
	});
	
	/*
	 * Prompts the user to save their new settings
	 */					
	$('#promptForSave').dialog({
			modal: true,
			autoOpen: false,
			resizable: false,
			zIndex: 2,
			buttons: {
				Yes: function() {
					// Save the new settings to flash
					$(this).dialog('close');
					saveSettings();
					updateStatus();				
				},
				No: function(){
					// Refresh the settings displayed in the UI
					$(this).dialog('close');
					updateSettings(settings);
				}
			}
	});	

	/*
	 * Opens the manual mode dialog box
	 */
	$('#manualChangeButton').click(function(){
		// If in schedule mode, notify the user the mode will be changing
		if(getOpMode() == "Schedule")
		{
				$('#manualModeDialog').dialog('open');
		}
		else
		{
            saveSettings();
		}
	});

	
	// Schedule set point dialog			
	$('#setPointDialog').dialog({
		autoOpen: false,
		width: 400,
		zIndex: 2,
		modal: true,
		resizable: false,
		title: "Add Set Point",
		buttons: {
			"Add Set Point": function() 
			{ 
				// Determine which button was pressed
				var success = false;
				var applyToDays = null;
				
				// Error Checking
				var time = getDesiredTime();
				var temp = getDesiredTemp();
				var applyToDays = getApplicableDays();
				
				// Attempt to add the value to the schedule(s)
				if (applyToDays == "oneDay") {
					addToSchedule(list, time, temp);
				}
				else if(applyToDays == "weekDays")
				{
					addToSchedule("#monScheduleList", time, temp);
					addToSchedule("#tuesScheduleList", time, temp);
					addToSchedule("#wedScheduleList", time, temp);
					addToSchedule("#thursScheduleList", time, temp);
					addToSchedule("#friScheduleList", time, temp);
				}
				else if (applyToDays == "weekEnd")
				{
					addToSchedule("#sunScheduleList", time, temp);
					addToSchedule("#satScheduleList", time, temp);
				}
				else if(applyToDays == "allDays")
				{
					addToSchedule("#sunScheduleList", time, temp);
					addToSchedule("#monScheduleList", time, temp);
					addToSchedule("#tuesScheduleList", time, temp);
					addToSchedule("#wedScheduleList", time, temp);
					addToSchedule("#thursScheduleList", time, temp);
					addToSchedule("#satScheduleList", time, temp);
					addToSchedule("#friScheduleList", time, temp);									
				}
				$(this).dialog("close");
			}, 
			"Cancel": function() 
			{ 
				$(this).dialog("close"); 
			} 
		}
	});
	
	// Necessary for newly-added set points to be able to be removed dynamically
	$('.removePoint').livequery('click', function() 
	{ 
		$(this).parent().parent().remove();					
		return false;
	});
					
	// Hover states on the static widgets
	$('.schedButton, #manualChangeButton, #saveThermostatSettings, #saveNetworkSettings, #applySchedule, #saveSchedule').hover(
		function() { $(this).addClass('ui-state-hover'); }, 
		function() { $(this).removeClass('ui-state-hover'); }
	);
								
	// Keep track of which day's button was clicked and what schedule we are modifying
	$('.schedButton').click(function()
	{
		day = $(this).attr("id");
		getSelectedDay();
		
		var curSize = $(list + ' li').size();
		if (curSize >= 4) {
			$('#maxSettingsDialog').dialog('open');					}
		else {
			$('#setPointDialog').dialog('open');
		}
		return false;
	});
	
	// Link navigation
	function hideAllContent(curLink)
	{
		// Hides all content panes except for the chosen one
		if (curLink != "schedule") {
			$('#scheduleContent').hide();
		}
		if(curLink != "manual")
		{
			$('#manualTempChange').hide();		
		}
		if(curLink != "historical")
		{
			$('#historicalContent').hide();			
		}
		if(curLink != "thermostatSettings")
		{
			$('#thermostatSettingsContent').hide();	
		}
		if(curLink != "networkSettings")
		{
			$('#networkSettingsContent').hide();
		}
		if(curLink!= "timeSettings")
		{
			$('#timeSettingsContent').hide();
		}
	};
	
	$('#schedule').click(function()
	{
		if (!checkForNewSettings()) {
			hideAllContent(this.id);
			changeLinkStyle(this.id);
			$('#scheduleContent').fadeIn("slow");
		}
		else{
			// Settings have been changed, so prompt to save them
			$('#promptForSave').dialog('open');
		}		
	});
	
	$('#manual').click(function()
	{
		if (!checkForNewSettings()) {
			hideAllContent(this.id);
			changeLinkStyle(this.id);
			$('#manualTempChange').fadeIn("slow");
		}
		else{
			// Settings have been changed, so prompt to save them
			$('#promptForSave').dialog('open');
		}		
	});
	
	$('#historical').click(function()
	{
		if (!checkForNewSettings()) {
			hideAllContent(this.id);
			changeLinkStyle(this.id);
			$('#historicalContent').fadeIn("slow");
		}
		else{
			// Settings have been changed, so prompt to save them
			$('#promptForSave').dialog('open');
		}		
	});

	$('#thermostatSettings').click(function()
	{
		if (!checkForNewSettings()) {
			hideAllContent(this.id);
			changeLinkStyle(this.id);
			$('#thermostatSettingsContent').fadeIn("slow");
		}
		else{
			// Settings have been changed, so prompt to save them
			$('#promptForSave').dialog('open');
		}		
	});

	$('#networkSettings').click(function()
	{
		if (!checkForNewSettings()) {
			hideAllContent(this.id);
			changeLinkStyle(this.id);
			getDHCPValue();
			$('#networkSettingsContent').fadeIn("slow");
		}
		else{
			// Settings have been changed, so prompt to save them
			$('#promptForSave').dialog('open');
		}		
	});	
	
	$('#timeSettings').click(function(){
		if(!checkForNewSettings())
		{
			hideAllContent(this.id);
			changeLinkStyle(this.id);
			$('#timeSettingsContent').fadeIn("slow");			
		}
		else{
			// Settings have been changed, so prompt to save them
			$('#promptForSave').dialog('open');
		}
	})
	
	$('input[name="dhcpEnabled"]').each(function(){
	    $(this).click(function(){
	        getDHCPValue();
	    });
	});
	
	// Makes the links appear bolded
	function changeLinkStyle(link)
	{
		// Reset all links to their original style
		resetLinkStyle();
		
		// Modify the particular clicked link to look bold and blue
		$('#' + link).removeClass("link");
		$('#' + link).addClass("selectedLink");		
	};
	
	// Resets the style on all links to the original
	function resetLinkStyle()
	{
		$('#schedule').removeClass("selectedLink");
		$('#schedule').addClass("link");
		$('#manual').removeClass("selectedLink");
		$('#manual').addClass("link");
		$('#historical').removeClass("selectedLink");		
		$('#historical').addClass("link");
		$('#thermostatSettings').removeClass("selectedLink");
		$('#thermostatSettings').addClass("link");
		$('#networkSettings').removeClass("selectedLink");		
		$('#networkSettings').addClass("link");
		$('#timeSettings').removeClass("selectedLink");		
		$('#timeSettings').addClass("link");
	};
	
	// The Time Picker's functionality
	$("#clockPick").clockpick(
	{
		starthour: 0,
		endhour: 23,
		valuefield: 'time',
		layout: 'vertical',
		zIndex: 1000
	});
		
	// The temperature slider's functionality
	$(function() 
	{
		$("#slider").slider(
		{
			orientation: "horizontal",
			range: "min",
			min: 50,
			max: 80,
			value: 72,
			step: 1,
			slide: function(event, ui) 
			{
				$("#amount").val(ui.value);
			}
			});
			$("#amount").val($("#slider").slider("value"));
	});

	// The manual temperature change slider's functionality
	$(function() 
	{
		$("#manual_slider").slider(
		{
			orientation: "horizontal",
			range: "min",
			min: 50,
			max: 80,
			value: 72,
			step: 1,
			slide: function(event, ui) 
			{
				$("#manual_amount").val(ui.value);
			}
			});
		$("#manual_amount").val($("#manual_slider").slider("value"));
	});
	
	// The variance slider's functionality
	$(function() 
	{
		$("#var_slider").slider(
		{
			orientation: "horizontal",
			range: "min",
			min: 1,
			max: 3,
			value: 2,
			step: 1,
			slide: function(event, ui) 
			{
				$("#var_amount").val(ui.value);
			}
		});
		$("#var_amount").val($("#var_slider").slider("value"));
	});			

	// The thermostat polling slider's functionality
	$(function() 
	{
		$("#poll_slider").slider(
		{
			orientation: "horizontal",
			range: "min",
			min: 15,
			max: 120,
			value: 15,
			step: 15,
			slide: function(event, ui) 
			{
				$("#poll_amount").val(ui.value);
			}
		});
		$("#poll_amount").val($("#poll_slider").slider("value"));
	});					

	// Events for clicking "Save Settings" on the General Settings page
	$('#saveThermostatSettings').click(function(){
		var valid = true;
		if(getHVACMode() == undefined)
		{
			$('#settingsIncomplete').dialog('open');
			valid = false;
		}
		if(getOpMode() == undefined)
		{
			$('#settingsIncomplete').dialog('open');
			valid = false;
		}
		if(getFanSetting() == undefined)
		{
			$('#settingsIncomplete').dialog('open');
			valid = false;
		}
		if(getHeaterType() == undefined)
		{
			$('#settingsIncomplete').dialog('open');
			valid = false;
		}
		if($('#tempOffset').val() == "")
		{
			$('#settingsIncomplete').dialog('open');
			valid = false;
		}
		// All required information is on the page
		if(valid)
		{
			saveSettings();
		}
	});
	
	// Events for clicking "Save Settings" on the Network Settings page
	$('#saveNetworkSettings').click(function(){
		var valid = true;
		if (getDHCPValue() == "") 
		{
			$('#invalidDHCP').dialog('open');
			valid = false;
		}	
/*		else if(!validateMAC())
		{
			$('#invalidMAC').dialog('open');
			valid = false;
		}
*/		else if(!validateSSID())
		{
			$('#invalidSSID').dialog('open');
			valid = false;
		}
		else if(!validateWEPKey())
		{
			$('#invalidWEPKey').dialog('open');
			valid = false;
		}			
		
		// Only validate the IP, Netmask, and Gateway if DHCP is not enabled
		else if(getDHCPValue() == "No")
		{
			if(!validateIP())
			{
			$('#invalidIP').dialog('open');
				valid = false;
			}
			else if(!validateNetmask())
			{
			$('#invalidSubnet').dialog('open');
				valid = false;
			}
			else if(!validateGateway())
			{
			$('#invalidGateway').dialog('open');
				valid = false;
			}
			else if(!validateDNS())
			{
				$('#invalidDNS').dialog('open');
			}
		}
		
		// The entire form is good to set up and save the settings
		if(valid)
		{
		    saveSettings();
		}
		
	});

	// Events for clicking "Save Schedule" on the Schedule Control page.
	// This only saves the schedule but does not apply it.
	$('#saveSchedule').click(function(){
		saveSchedule();
	});

	$('#saveTimeSettings').click(function(){
		// TODO:  Save time zone settings to flash
		saveSettings();
	});	
	
	// Events for clicking "Apply Schedule" on the Schedule Control page.
	// This button first saves and then applies the schedule
	$('#applySchedule').click(function(){
		// Notify the user if switching from Manual mode
		if(getOpMode() == "Manual")
		{
			$('#switchingToScheduleDialog').dialog('open');
		}
		else
		{
			saveSchedule();
		}
	});

	// Clear historical data
	$('#clearHistory').click(function(){
		$('#heatRuntimeHr').val("0");
		$('#heatRuntimeMin').val("0");		
		$('#acRuntimeHr').val("0");
		$('#acRuntimeMin').val("0");
		$('#fanRuntimeHr').val("0");
		$('#fanRuntimeMin').val("0");
		
		// Save settings to update the data
		//saveSettings();		
	})
	
	// Check if settings have been changed before moving to a new page
	function checkForNewSettings()
	{
		if(settings.macAddr1 != $('#macAddr1').val()){
			return true;
		}
		else if(settings.macAddr2 != $('#macAddr2').val()){
			return true;
		}
		else if(settings.macAddr3 != $('#macAddr3').val()){
			return true;
		}
		else if(settings.macAddr4 != $('#macAddr4').val()){
			return true;
		}
		else if(settings.macAddr5 != $('#macAddr5').val()){
			return true;
		}
		else if(settings.macAddr6 != $('#macAddr6').val()){
			return true;
		}
		else if(settings.dhcpEnabled != $('input[name="dhcpEnabled"]:checked').val()){
			return true;
		}
		else if(settings.ipAddr1 != $('#ipAddr1').val()){
			return true;
		}
		else if(settings.ipAddr2 != $('#ipAddr2').val()){
			return true;
		}
		else if(settings.ipAddr3 != $('#ipAddr3').val()){
			return true;
		}
		else if(settings.ipAddr4 != $('#ipAddr4').val()){
			return true;
		}
		else if(settings.inetMask1 != $('#inetMask1').val()){
			return true;
		}	
		else if(settings.inetMask2 != $('#inetMask2').val()){
			return true;
		}	
		else if(settings.inetMask3 != $('#inetMask3').val()){
			return true;
		}	
		else if(settings.inetMask4 != $('#inetMask4').val()){
			return true;
		}	
		else if(settings.gatewayAddr1 != $('#gatewayAddr1').val()){
			return true;
		}	
		else if(settings.gatewayAddr2 != $('#gatewayAddr2').val()){
			return true;
		}	
		else if(settings.gatewayAddr3 != $('#gatewayAddr3').val()){
			return true;
		}
		else if(settings.gatewayAddr4 != $('#gatewayAddr4').val()){
			return true;
		}
		else if(settings.dnsAddr1 != $('#DNSAddr1').val()){
			return true;
		}	
		else if(settings.dnsAddr2 != $('#DNSAddr2').val()){
			return true;
		}	
		else if(settings.dnsAddr3 != $('#DNSAddr3').val()){
			return true;
		}
		else if(settings.dnsAddr4 != $('#DNSAddr4').val()){
			return true;
		}
		else if(settings.ssid != $('#ssid').val()){
			return true;
		}
		else if(settings.wepKey != $('#wepKey').val()){
			return true;
		}
		else if(settings.manualTemp != $('#manual_amount').val()){
			return true;
		}
		else if(settings.tempVariance != $('#var_amount').val()){
			return true;
		}
		else if(settings.setHVACMode != $('input[name="setHVACMode"]:checked').val()){
			return true;
		}
		else if(settings.setFanMode != $('input[name="setFanMode"]:checked').val()){
			return true;
		}
		else if(settings.myHeaterType != $('input[name="myHeaterType"]:checked').val()){
			return true;
		}
		else if(settings.opMode != $('input[name="opMode"]:checked').val()){
			return true;
		}
		else if(settings.pollInterval != $('#poll_amount').val()){
			return true;
		}
		else if(settings.tempOffset != $('#tempOffset').val()){
			return true;
		}
		else if(settings.autoTimeSync != $('#autoTimeSync').attr('checked')){
			return true;
		}
		else if(settings.daylightSavingEnabled != $('#useDaylightSavings').attr('checked')){
			return true;
		}
		else if(settings.timeServerAddress != $('#timeServerField').val()){
			return true;
		}
		else if(settings.timeZone != $('#timeZone').val()){
			return true;
		}
		else{
			// None of the settings have changed
			return false;			
		}

	};
	
}); // End of Document Ready function

// Get the value of the radio button for Cool, Heat, or Off
function getHVACMode()
{
	var ret_val;
	for (var i=0; i < document.HVACModeForm.setHVACMode.length; i++)
   	{
   		if (document.HVACModeForm.setHVACMode[i].checked)
     	{
      		ret_val = document.HVACModeForm.setHVACMode[i].value;
	  		break;
      	}
   	}
   	return ret_val;
}

// Get the temperature setting (desired temperature)
function getDesiredTemp()
{
	var ret_val = document.temperature.desiredTemp.value;
	return ret_val;
}

// Get the desired time
function getDesiredTime()
{
	var ret_val = document.timeSelector.time.value;
	return ret_val;
}

// Get fan setting (Auto or On)
function getFanSetting()
{
	var fan_mode;
	for (var i=0; i < document.fanModeForm.setFanMode.length; i++)
   	{
   		if (document.fanModeForm.setFanMode[i].checked)
    	{
     		fan_mode = document.fanModeForm.setFanMode[i].value;
	  		break;
    	}
   	}
	return fan_mode;
}

// Get system mode (Schedule or Manual)
function getOpMode()
{
	var ret_val;
	for (var i=0; i < document.opModeForm.opMode.length; i++)
   	{
   		if (document.opModeForm.opMode[i].checked)
    	{
     		ret_val = document.opModeForm.opMode[i].value;
	  		break;
    	}
   	}
	return ret_val;
}

// Set system mode (Schedule or Manual)
function setOpMode(mode)
{
	if(mode == "Schedule")
	{
		document.opModeForm.opMode[0].checked = true;
		document.opModeForm.opMode[1].checked = false;
	}
	else{
		document.opModeForm.opMode[1].checked = true;
		document.opModeForm.opMode[0].checked = false;
	}
}

// Get the type of heater set (Gas or Electric)
function getHeaterType()
{
	var ret_val;
	for (var i=0; i < document.myHeaterTypeForm.myHeaterType.length; i++)
   	{
   		if (document.myHeaterTypeForm.myHeaterType[i].checked)
    	{
     		ret_val = document.myHeaterTypeForm.myHeaterType[i].value;
	  		break;
    	}
   	}
	return ret_val;	
}
// Get temperature units (F or C)
function getTempUnits()
{
	var ret_val;
	for (var i=0; i < document.tempUnitForm.tempUnit.length; i++)
   	{
   		if (document.tempUnitForm.tempUnit[i].checked)
    	{
     		ret_val = document.tempUnitForm.tempUnit[i].value;
	  		break;
    	}
   	}
	return ret_val;
}			

// Get the tolerance setting
function getVariance()
{
	var ret_val = document.tempVarianceForm.desiredVar.value;
	return ret_val;
}			

// Gets the MAC address as a big string
function getMACAddress()
{
	ret_val = "";
	if (validateMAC()) {
		ret_val = ret_val + document.getElementById("macAddr1").value;
		ret_val = ret_val + document.getElementById("macAddr2").value;
		ret_val = ret_val + document.getElementById("macAddr3").value;
		ret_val = ret_val + document.getElementById("macAddr4").value;
		ret_val = ret_val + document.getElementById("macAddr5").value;
		ret_val = ret_val + document.getElementById("macAddr6").value;
	}
	return ret_val;
}

// Ensures all fields of the MAC address have been filled out
function validateMAC()
{
	var ret_val = true;
	if((document.getElementById("macAddr1").value.length < 2) || (document.getElementById("macAddr2").value.length < 2) || (document.getElementById("macAddr3").value.length < 2) || (document.getElementById("macAddr4").value.length < 2) || (document.getElementById("macAddr5").value.length < 2) || (document.getElementById("macAddr6").value.length < 2))
	{
		ret_val = false;
	}
	return ret_val;
}

// Gets the IP address as a big string
function getIPAddress()
{
	ret_val = "";
	if (validateIP()) {
		ret_val = ret_val + document.getElementById("ipAddr1").value;
		ret_val = ret_val + document.getElementById("ipAddr2").value;
		ret_val = ret_val + document.getElementById("ipAddr3").value;
		ret_val = ret_val + document.getElementById("ipAddr4").value;
	}
	return ret_val;
}

// Ensures all fields of the IP address have been filled out
function validateIP()
{
	var ret_val = true;
	if((document.getElementById("ipAddr1").value.length < 3) || (document.getElementById("ipAddr2").value.length < 3) || (document.getElementById("ipAddr3").value.length < 3) || (document.getElementById("ipAddr4").value.length < 3))
	{
		ret_val = false;
	}
	return ret_val;
}

// Gets the Subnet address as a big string
function getNetmask()
{
	ret_val = "";
	if (validateNetmask()) {
		ret_val = ret_val + document.getElementById("inetAddr1").value;
		ret_val = ret_val + document.getElementById("inetAddr2").value;
		ret_val = ret_val + document.getElementById("inetAddr3").value;
		ret_val = ret_val + document.getElementById("inetAddr4").value;
	}
	return ret_val;
}

// Ensures all fields of the Subnet address have been filled out
function validateNetmask()
{
	var ret_val = true;
	if((document.getElementById("inetMask1").value.length < 3) || (document.getElementById("inetMask2").value.length < 3) || (document.getElementById("inetMask3").value.length < 3) || (document.getElementById("inetMask4").value.length < 3))
	{
		ret_val = false;
	}
	return ret_val;
}

// Gets the Gateway address as a big string
function getGateway()
{
	ret_val = "";
	if (validateGateway()) {
		ret_val = ret_val + document.getElementById("gatewayAddr1").value;
		ret_val = ret_val + document.getElementById("gatewayAddr2").value;
		ret_val = ret_val + document.getElementById("gatewayAddr3").value;
		ret_val = ret_val + document.getElementById("gatewayAddr4").value;
	}
	return ret_val;
}

// Ensures all fields of the Gateway address have been filled out
function validateGateway()
{
	var ret_val = true;
	if((document.getElementById("gatewayAddr1").value.length < 3) || (document.getElementById("gatewayAddr2").value.length < 3) || (document.getElementById("gatewayAddr3").value.length < 3) || (document.getElementById("gatewayAddr4").value.length < 3))
	{
		ret_val = false;
	}
	return ret_val;
}

// Gets the DNS Server address as a big string
function getDNS()
{
	ret_val = "";
	if (validateDNS()) {
		ret_val = ret_val + document.getElementById("DNSAddr1").value;
		ret_val = ret_val + document.getElementById("DNSAddr2").value;
		ret_val = ret_val + document.getElementById("DNSAddr3").value;
		ret_val = ret_val + document.getElementById("DNSAddr4").value;
	}
	return ret_val;
}

// Ensures all fields of the DNS address have been filled out
function validateDNS()
{
	var ret_val = true;
	if((document.getElementById("DNSAddr1").value.length < 3) || (document.getElementById("DNSAddr2").value.length < 3) || (document.getElementById("DNSAddr3").value.length < 3) || (document.getElementById("DNSAddr4").value.length < 3))
	{
		ret_val = false;
	}
	return ret_val;
}

// Gets the SSID as one big string
function getSSID()
{
	ret_val = "";
	if(validateSSID())
	{
		ret_val = document.getElementById("ssid").value;		
	}
	return ret_val;
}

// Checks whether the SSID has something in its field
function validateSSID()
{
	var ret_val = true;
	if(document.getElementById("ssid").value.length < 1)
	{
		ret_val = false;
	}
	return ret_val;
}

// Gets the WEP Key as one long string
function getWEPKey()
{
	ret_val = "";
	if(validateWEPKey())
	{
		ret_val = document.getElementById("wepKey").value;		
	}
	return ret_val;
}

// Checks whether the WEP key is of valid length
function validateWEPKey()
{
	var ret_val = true;
	
	// WEP Key must either be 10 or 26 characters long (depending on the version of WEP being used)
	if(document.getElementById("wepKey").value.length != 0 && document.getElementById("wepKey").value.length != 10 && document.getElementById("wepKey").value.length != 26)
	{
		ret_val = false;
	}
	return ret_val;
}

// Gets the days of the week to apply the thermostat setting to
function getApplicableDays()
{
	var ret_val = document.daysSelector.applicableDays.value;
	return ret_val;
}

/*
 * Helper functions
 */				
 
// Get the day that was clicked on
function getSelectedDay()
{
	if(day == "addPointSun")
	{
		list = "#sunScheduleList";
	}
	else if(day =="addPointMon")
	{
		list = "#monScheduleList";
	}
	else if(day == "addPointTues")
	{
		list = "#tuesScheduleList";
	}
	else if(day == "addPointWed")
	{
		list = "#wedScheduleList";
	}
	else if(day == "addPointThurs")
	{
		list = "#thursScheduleList";
	}
	else if(day == "addPointFri")
	{
		list = "#friScheduleList";
	}
	else if(day == "addPointSat")
	{
		list = "#satScheduleList";
	}
};

/*
 * Get the time in minutes since midnight
 */	
function get_time_mins(time)
{
	var date = new Date("Jan 1, 1970 " + time);
	var mins = date.getHours() * 60 + date.getMinutes();
	return mins;
};

/*
 * Add the current setting to the schedule on a specific day
 */
function addToSchedule(schedule, time, temp)
{
	// Error checking for valid values and full schedules
	
	// Check to see if the list is already full (5 entries)
	var curSize = $(schedule + ' li').size();
	
	// Get time in minutes since midnight
	var timeInMins = get_time_mins(time);
	if (curSize >= 4) 
	{
		$('#maxSettingsDialogMultiple').dialog('open');
	}
	else if(time == "")
	{
		$('#invalidTimeDialog').dialog('open');
	}
	else if(timeInSchedule(timeInMins, schedule))
	{
		$('#timeExistsDialog').dialog('open');
	}
	else if(temp > 80 || temp < 50)
	{
		$('#invalidTempDialog').dialog('open');
	}
	else
	{						
		// Add the new schedule time
		$('<li><span>' + time + '</span><span class="hiddenTime">' + timeInMins + '</span>&nbsp;&nbsp;-&nbsp;<span class="temp">' + temp + ' F</span>&nbsp;&nbsp;<span><img src="images/remove.png" class="removePoint"></span></li>').appendTo(schedule);	

		// Sort the schedule
		sortSchedule(schedule);
		
		return true;	
	}
};			

// Checks to see if the time already has a thermostat set point in the schedule
function timeInSchedule(time, schedule)
{
	retVal = false;
	var temp = $(schedule + ' li span:hidden').each(function(){
		if($(this).text() == time)
		{
			retVal = true;
		}
	});
	return retVal;	
};

// Sorts the schedule based on time values for the set points
function sortSchedule(schedule)
{
	$("ul" + schedule + ">li").tsort("span[class=hiddenTime]");		
};

// Checks if DHCP is enabled, and if so, disables the IP Address, Netmask, Gateway, and DNS Server fields
function getDHCPValue()
{
	var dhcp_val;
	var ret_val;
	for (var i=0; i < document.DHCPForm.dhcpEnabled.length; i++)
   	{
   		if (document.DHCPForm.dhcpEnabled[i].checked)
     	{
      		dhcp_val = document.DHCPForm.dhcpEnabled[i].value;
			break;
      	}
   	}
	if(dhcp_val == "Yes")
	{
		// Disable the IP Address, Netmask, and gateway fields
		$('#ipAddress').hide();
		$('#subnetMask').hide();
		$('#defaultGateway').hide();
		$('#DNSServer').hide();
		ret_val = dhcp_val;
	}
	else if(dhcp_val == "No")
	{
		// Show all of the fields if they have selected "No"
		$('#ipAddress').show();
		$('#subnetMask').show();
		$('#defaultGateway').show();
		$('#DNSServer').show();
		ret_val = dhcp_val;
	}
	else
	{
		// Nothing was selected, so show everything
		$('#ipAddress').show();
		$('#subnetMask').show();
		$('#defaultGateway').show();
		$('#DNSServer').show();
		ret_val = "";
	}
   	return ret_val;				
};
